package com.kczd.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.kczd.client.R;
import com.kczd.util.Common;
import com.kczd.util.StringSaveUtil;
import com.kczd.util.SysApplication;
import com.swwx.paymax.PayResult;
import com.swwx.paymax.PaymaxCallback;
import com.swwx.paymax.PaymaxSDK;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PayMaxActivity extends AppCompatActivity implements PaymaxCallback {

    protected String amount = "";
    protected String userid = "";
    String startPos,startlat,startlgt,body,clientip,endPos,endlat,endPgt,cash;

    private int channel = PaymaxSDK.CHANNEL_ALIPAY;
    private TextView mPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_max);

        // 多activity管理
        SysApplication.getInstance().addActivity(this);

        cash = getIntent().getStringExtra("amount");
        amount = formateRate(cash);
        startPos = getIntent().getStringExtra("startPos");
        startlat = getIntent().getStringExtra("startlat");
        startlgt = getIntent().getStringExtra("startlgt");
        userid = getIntent().getStringExtra("ukey");
        body = getIntent().getStringExtra("body");
        clientip = getIntent().getStringExtra("clientip");
        endPos = getIntent().getStringExtra("endPos");
        endlat = getIntent().getStringExtra("endlat");
        endPgt = getIntent().getStringExtra("endPgt");
        mPrice= (TextView) findViewById(R.id.d_amount);//车费合计
        mPrice.setText(amount);

    }

    public void onCharge(View view) {
        if (checkInputValid(amount)) {
            switch (channel) {
                case PaymaxSDK.CHANNEL_ALIPAY:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            loginHandle();
                        }
                    }).start();
                    break;
            }
        }
    }
    String url = Common.net_addr +"itf/tx_pay.php";
    public void loginHandle() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("ukey", Common.user.getUkey())
                .add("startPos",startPos)
                .add("start_lat", startlat)
                .add("start_lgt", startlgt)
                .add("endPos", endPos)
                .add("end_lat", endlat)
                .add("end_lgt", endPgt)
                .add("amount", amount)
                .add("subject", "打车")
                .add("body", body)
                .add("channel","alipay_app")
                .add("client_ip",clientip)
                .build();

        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();

           if(response.code() == 200) {
               Message msg = new Message();
               Bundle data = new Bundle();
               data.putString("ret_json", strResult);
               msg.setData(data);
               handle.sendMessage(msg);
           }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private String id=null;
    private String okey=null;
    String callurl = Common.net_addr +"itf/tx_retrieve.php";
    Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e("val",val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonObject=null;
            try {
                 jsonObject=new JSONObject(val);
                 id=jsonObject.getString("id");
                okey=jsonObject.getString("order_no");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e("zhangy",val);
            PaymaxSDK.pay(PayMaxActivity.this,val,PayMaxActivity.this);

        }
    };

    @Override
    public void onPayFinished(PayResult result) {
        String msg = "Unknow";
        switch (result.getCode()) {
            case PaymaxSDK.CODE_SUCCESS:
                msg = "Complete, Success!.";
                Log.e("id",id);
               if(id!=null){
                   OkHttpClient okHttpClient=new OkHttpClient();
                   RequestBody requestBody=new FormBody.Builder()
                           .add("id",id)
                           .build();
                   Request request=new Request.Builder()
                           .url(callurl)
                           .post(requestBody)
                           .build();
                   try {
                       Response response=okHttpClient.newCall(request).execute();
                       if(response.code() == 200) {
                           //1、当支付成功的时候，将订单id保存
                           StringSaveUtil.cachedOkey(PayMaxActivity.this, okey);

                           Intent intent = new Intent(PayMaxActivity.this, MainActivity.class);
                           intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                           startActivity(intent);
                           finish();
                       }
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
                break;
            case PaymaxSDK.CODE_ERROR_CHARGE_JSON:
                msg = "Json error.";
                break;

            case PaymaxSDK.CODE_FAIL_CANCEL:
                msg = "cancel pay.";
                break;

            case PaymaxSDK.CODE_ERROR_CHARGE_PARAMETER:
                msg = "appid error.";
                break;

            case PaymaxSDK.CODE_ERROR_WX_NOT_INSTALL:
                msg = "wx not install.";
                break;

            case PaymaxSDK.CODE_ERROR_WX_NOT_SUPPORT_PAY:
                msg = "ex not support pay.";
                break;

            case PaymaxSDK.CODE_ERROR_WX_UNKNOW:
                msg = "wechat failed.";
                break;

            case PaymaxSDK.CODE_ERROR_ALI_DEAL:
                msg = "alipay dealing.";
                break;

            case PaymaxSDK.CODE_ERROR_ALI_CONNECT:
                msg = "alipay network connection failed.";
                break;

            case PaymaxSDK.CODE_ERROR_CHANNEL:
                msg = "channel error.";
                break;
        }
    }

    private boolean checkInputValid(String amountText) {
        return !(null == amountText || amountText.length() == 0);
    }

    public String formateRate(String rateStr){
        if(rateStr.indexOf(".") != -1){
            //获取小数点的位置
            int num = 0;
            num = rateStr.indexOf(".");

            //获取小数点后面的数字 是否有两位 不足两位补足两位
            String dianAfter = rateStr.substring(0,num+1);
            String afterData = rateStr.replace(dianAfter, "");
            if(afterData.length() < 2){
                afterData = afterData + "0" ;
            }else{
            }
            return rateStr.substring(0,num) + "." + afterData.substring(0,2);
        }else{
            if(rateStr == "1"){
                return "100";
            }else{
                return rateStr;
            }
        }
    }

}
